<?php

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class Domain extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('domain')
            ->setDescription('the test command');        
    }

    protected function execute(Input $input, Output $output){

        $access_key = 'LTAI4GDtdw1eiiwk5wprALWP';
        $access_secret = '9e3vKsh7g0tqgnl647cUMXVmtPMlgC';

        AlibabaCloud::accessKeyClient($access_key, $access_secret)
            ->regionId('cn-hangzhou')
            ->asDefaultClient();

        $this->getDomainList();
        //$this->checkDomain();
         return 'ok';
    }


    //获取域名列表
    public function getDomainList($page=1){

        try {
            //获取阿里云接口域名列表
            $result = AlibabaCloud::rpc()
                ->product('Domain')
                ->version('2018-01-29')
                ->action('QueryDomainList')
                ->method('POST')
                ->host('domain.aliyuncs.com')
                ->options([
                    'query' => [
                        'PageNum' => $page,
                        'PageSize' => 10,
                        'Lang' => 'zh',
                    ],
                ])
                ->request()
                ->toArray();

            $list = isset($result['Data']['Domain']) ? $result['Data']['Domain'] : [];
            if(!$list){
                return true;
            }
            $add_list = [];
            foreach ($list as $k=>$v){

                switch ($v['DomainAuditStatus']){
                    case 'SUCCEED':
                        $audit_status = 1;     //实名认证成功
                        break;
                    case 'AUDITING':
                        $audit_status = 2;     //审核中
                        break;
                    case 'FAILED':
                        $audit_status = 3;     //实名认证失败
                        break;
                    case 'NONAUDIT':
                        $audit_status = 4;      //未实名认证
                        break;
                    default:
                        $audit_status = 0;      //异常
                        break;
                }

                $info = [
                    'domain' => $v['DomainName'],                       //域名
                    'domain_status' => $v['DomainStatus'],              //域名状态 1：急需续费 2：急需赎回 3：正常
                    'audit_status'  => $audit_status,                   //域名实名认证状态 1:实名认证成功  2:审核中 3:实名认证失败 4:未实名认证 0:异常
                    'expire_num'    => $v['ExpirationCurrDateDiff'],    //域名到期剩余天数
                    'expire_time'   => strtotime($v['ExpirationDate']), //域名到期日期
                    'expire_status' => $v['ExpirationDateStatus'],      //域名过期状态 1：域名未过期  2：域名已过期
                    'regist_type'   => $v['RegistrantType'],            //域名注册类型。1：个人 2：企业
                    'regist_time'   => strtotime($v['RegistrationDate']),//注册时间
                    'create_time'   => time()
                ];
                
                $res = Db::table('domain')->where('domain',$v['DomainName'])->field('id')->find();
                if($res){
                    Db::table('domain')->where('id',$res['id'])->update($info);
                }else{
                    array_push($add_list,$info);
                }
            }

            if($add_list){
                Db::table('domain')->insertAll($add_list);
            }

            //下一页
            if($result['NextPage']){
                self::getDomainList($result['CurrentPageNum']+1);
            }

            return true;

        } catch (ClientException $e) {
            return $e->getErrorMessage() . PHP_EOL;

        } catch (ServerException $e) {
            return $e->getErrorMessage() . PHP_EOL;
        }

    }

    //检验域名是否掉备案
    public function checkDomain(){
        $list = Db::table('domain')->where(['domain_status'=>3,'audit_status'=>1])->field('id,domain')->select();
        if(!$list){
            return false;
        }

        foreach ($list as $k=>$v){
            $url = 'http://'.$v['domain'].'/';
//            $url = 'http://lsbgc68.cn/';
            try{

                $url = "http://icp.chinaz.com/bigbigboy.top";
                $res = trim(file_get_contents($url));
                //dump(trim($res));die;
                //$res = htmlspecialchars($res);
                //file_put_contents('aaa.log',$res);die;
                preg_match('//i',$res,$list);
                dump($list);
               
            }catch (Exception  $e) {

            }


        }
        
    }


    //curl_get 请求
    public function curlGet($url){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        dump($aStatus);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }

    }

    //curl_post 请求
    public function curlPost($url,$param,$post_file=false){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) {
            $is_curlFile = true;
        } else {
            $is_curlFile = false;
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
            }
        }
        if (is_string($param)) {
            $strPOST = $param;
        }elseif($post_file) {
            if($is_curlFile) {
                foreach ($param as $key => $val) {
                    if (substr($val, 0, 1) == '@') {
                        $param[$key] = new \CURLFile(realpath(substr($val,1)));
                    }
                }
            }
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach($param as $key=>$val){
                $aPOST[] = $key."=".urlencode($val);
            }
            $strPOST =  join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($oCurl, CURLOPT_POST,true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }



}
